<?php
/**
 * 商品分类 api
 * @author maniac
 */
namespace app\api\controller\v1;

use app\facade\Slides;
use app\facade\GoodCategory AS GoodCategoryFacade;
use app\facade\GoodMods;

class GoodCategory extends Base
{
    /**
     * 商品分类页接口
     */
    public function index()
    {
        $parent_id=input("parent_id",0);
        // 商品分类头部 banner
        $slides     = Slides::slides(2, 5);
        // 获取商品分类
        $wheresqlarr=[];
        $wheresqlarr[]=['is_show',"=",1];
        $wheresqlarr[]=['parent_id',"=",$parent_id];

        $categories = GoodCategoryFacade::categories($wheresqlarr);
        $ids=[];
        foreach ($categories as $k=>$v){
            $ids[]=$v["id"];
        }
        $pids=[];
        $tmp=[];
        if(empty($parent_id)) {
            foreach ($categories as $k => $v) {
                $item = [
                    "id" => $v["id"],
                    "pid" => $v["parent_id"],
                    "name" => $v["name"],
                    "picture" => "",
                ];
                if ($item["pid"] == 0) {
                    $tmp[] = $item;
                } else {
                    //增加二级分类
                    if (!key_exists($v["parent_id"], $pids)) {
                        $new_id = max($ids) + 1;
                        $ids[] = $new_id;
                        $pids[$v["parent_id"]] = $new_id;
                        $item = [
                            "id" => $new_id,
                            "pid" => $v["parent_id"],
                            "name" => $v["parent_name"],
                            "picture" => "",
                        ];
                        $tmp[] = $item;
                    }

                    //原二级类变为三级类
                    $item = [
                        "id" => $v["id"],
                        "pid" => $pids[$v["parent_id"]],
                        "name" => $v["name"],
                        "picture" => $v["image_uri"],
                    ];
                    $tmp[] = $item;
                }
            }
        }
        $data = [
            //'slides' => $slides,
            'data'   => $categories,
            'tmp'=>$tmp
        ];
        return j(0, '获取商品分类数据成功', $data);
    }
    
    /**
     * 获取商品分类关联模型
     * @param  int $category_id 分类 id
     */
    public function categoryMod($category_id = 0)
    {
        $category = GoodCategoryFacade::categories(['id' => $category_id])[0];
        if ($category['good_mods_id']) {
            $data = GoodMods::mod($category['good_mods_id']);
            $data['mods'] = $category;
            return j(0, '获取商品模型成功', $data);
        }
        return j(1, '获取商品模型视频');
    }
}
